// 封装路由操作可以在非组件的环境下使用(如: axios拦截器)

// https://reactnavigation.org/docs/navigating-without-navigation-prop
import { createNavigationContainerRef } from "@react-navigation/native";
import { StackActions } from "@react-navigation/native";

import type { RootStackParamList } from "@/router/routerType";
export const navigationRef = createNavigationContainerRef<RootStackParamList>();

type ScreenName = keyof RootStackParamList;

const navigate = (name: ScreenName, ...args: any[]) => {
  if (navigationRef.isReady()) {
    // @ts-ignore
    navigationRef.navigate(name, ...args);
  }
};

const replace = (name: ScreenName, ...args: any[]) => {
  if (navigationRef.isReady()) {
    navigationRef.dispatch(StackActions.replace(name, ...args));
  }
};

const back = () => {
  if (navigationRef.isReady()) {
    navigationRef.dispatch(StackActions.pop());
  }
};

const getRouter = () => {
  if (navigationRef.isReady()) {
    return navigationRef.getCurrentRoute();
  }
};

export default {
  navigate,
  replace,
  back,
  getRouter
};
